<template>
  <q-layout view="lHr LpR lFr">
    <q-header bordered class="bg-primary text-white">
      <q-toolbar>
        <q-btn
          flat
          dense
          round
          icon="menu"
          aria-label="Menu"
          @click="toggleLeftDrawer"
        />
        <div class="col relative-position gradient-text-box">
          <q-toolbar-title class="cursor-pointer gradient-text">
            {{ useSettingStores().pageTitle }}

            <q-popup-edit
              v-model="useSettingStores().pageTitle"
              @Save="useSettingStores().changePageTitle"
              :cover="false"
              :offset="[0, 10]"
              v-slot="scope"
            >
              <q-input
                autofocus
                dense
                v-model="scope.value"
                :model-value="scope.value"
              >
                <template v-slot:after>
                  <q-btn
                    flat
                    dense
                    color="negative"
                    icon="cancel"
                    @click.stop.prevent="scope.cancel"
                  />

                  <q-btn
                    flat
                    dense
                    color="positive"
                    icon="check_circle"
                    @click.stop.prevent="scope.set"
                    :disable="scope.initialValue === scope.value"
                  />
                </template>
              </q-input>
            </q-popup-edit>
          </q-toolbar-title>
        </div>
        <q-btn
          flat
          dense
          round
          icon="settings"
          aria-label="Settings"
          @click="toggleRightDrawer"
        />
      </q-toolbar>
    </q-header>

    <q-drawer v-model="leftDrawerOpen" show-if-above bordered>
      <div class="drawer-content">
        <!-- 顶部固定部分 -->
        <div class="drawer-header">
          <q-toolbar class="bg-primary text-white">
            <q-btn
              flat
              dense
              round
              icon="menu"
              aria-label="Menu"
              @click="toggleLeftDrawer"
              stamp="7 minutes ago"
            />
            <q-space />
            <q-btn
              flat
              round
              dense
              icon="maps_ugc"
              @click.prevent="useMsgStores().newChat(1)"
            >
            </q-btn>
          </q-toolbar>
        </div>

        <!-- 中间滚动部分 -->
        <q-scroll-area class="drawer-body">
          <q-list>
            <EssentialLink
              v-for="link in linksList"
              :key="link.title"
              v-bind="link"
            />
          </q-list>
        </q-scroll-area>

        <!-- 底部固定部分 -->
        <div class="drawer-footer">
          <q-item clickable @click="openForm">
            <q-item-section avatar>
              <q-icon name="forward_to_inbox" />
            </q-item-section>

            <q-item-section>
              <q-item-label>问题反馈</q-item-label>
            </q-item-section>
          </q-item>
        </div>
      </div>
    </q-drawer>

    <q-drawer v-model="rightDrawerOpen" show-if-above bordered side="right">
      <q-toolbar class="bg-primary text-white shadow-2">
        <q-space />

        <q-btn
          flat
          dense
          round
          icon="settings"
          aria-label="Settings"
          @click="toggleRightDrawer"
          stamp="7 minutes ago"
        />
        <!-- <q-btn
          flat
          round
          dense
          icon="maps_ugc"
          @click.prevent="useMsgStores().newChat(1)"
        >
        </q-btn> -->
      </q-toolbar>
      <q-list>
        <q-item tag="label" v-ripple>
          <q-item-section>
            <q-item-label>爱心发射biu~biu~biu</q-item-label>
          </q-item-section>
          <q-item-section side>
            <q-toggle
              checked-icon="check"
              unchecked-icon="clear"
              color="blue"
              v-model="useSettingStores().lovingState"
              @Update:modelValue="useSettingStores().changeLovingState"
              val="battery"
            />
          </q-item-section>
        </q-item>
      </q-list>
    </q-drawer>

    <q-page-container>
      <router-view />
    </q-page-container>
    <!-- 透明 -->
    <q-footer class="bg-white q-pa-xs">
      <div class="image-container" v-if="images.length">
        <div v-for="(image, index) in images" :key="index" class="image-item">
          <q-img
            :src="image"
            class="preview-image"
            :alt="'Uploaded Image ' + (index + 1)"
            :ratio="1"
          />
          <q-btn
            icon="delete"
            color="red"
            class="delete-button"
            @click="removeImage(index)"
            size="xs"
            dense
          />
        </div>
      </div>
      <div class="chat-container">
        <q-uploader
          url=""
          @added="handleFilesAdded"
          multiple
          max-files="1"
          ref="fileInput"
          :auto-upload="false"
          style="display: none"
        >
        </q-uploader>
        <q-input
          v-model="textareaModel"
          rounded
          outlined
          autogrow
          type="textarea"
          :input-style="{ maxHeight: '200px' }"
          style="
            width: 100%;
            align-items: flex-end;
            max-width: 768px;
            padding: 16px;
          "
        >
          <template v-slot:prepend>
            <div>
              <q-btn
                :disable="isLoading || imagesLoading"
                :loading="imagesLoading"
                round
                color="primary"
                @click="uploadFile()"
                icon="cloud_upload"
              />
              <!-- <q-btn
              /> -->
            </div>
          </template>

          <template v-slot:append>
            <q-btn
              round
              color="primary"
              icon="navigation"
              :loading="isLoading"
              :disable="!textareaModel || imagesLoading"
              @click="sendMessage"
            />
          </template>
        </q-input>
      </div>
    </q-footer>
  </q-layout>

  <q-dialog v-model="prompt" persistent>
    <q-card style="min-width: 350px">
      <q-card-section>
        <div class="text-h6">意见反馈</div>
      </q-card-section>

      <q-card-section class="q-pt-none">
        <q-input dense v-model="emailMsg"> </q-input>
      </q-card-section>

      <q-card-actions align="right" class="text-primary">
        <q-btn flat label="取消" v-close-popup />
        <q-btn
          flat
          label="发送邮件"
          :loading="fasonyoujLoading"
          @click="sendEmail"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import EssentialLink from 'components/EssentialLink.vue';
import { useMsgStores } from 'src/stores/msgStores';
import { useSettingStores } from 'src/stores/settingStores';
import { getGptReply } from 'src/api/openai.js';
import { useRoute } from 'vue-router';
import { postSendEmail, postUploads } from 'src/api/manage.js';
import { Notify } from 'quasar';
// import ForwardComponents from 'components/Forward.vue';
const prompt = ref(false);
const fasonyoujLoading = ref(false);
const emailMsg = ref('');
const route = useRoute();
defineOptions({
  name: 'MainLayout'
});
const textareaModel = ref('');
const isLoading = ref(false); // 接口调用的加载状态
const lovingTime = ref(null);
const fileInput = ref(null);

function uploadFile() {
  fileInput.value.pickFiles(); // 手动触发 q-file 的文件选择
  if (isLoading.value) return;
}

const files = ref([]);
const images = ref([]); // 用于存储图像 URL
const imagesLoading = ref(false);
// watch(
//   () => files.value,
//   newFile => {
//     // 生成图像 URL
//     images.value = newFile.map(file => URL.createObjectURL(file));
//   }
// );
async function handleFilesAdded(newFiles) {
  try {
    // 添加文件时，检查是否重复
    imagesLoading.value = true;
    newFiles.forEach(newFile => {
      if (
        !files.value.find(
          file => file.name === newFile.name && file.size === newFile.size
        )
      ) {
        files.value.push(newFile);
      }
    });
    // 更新q-uploader的文件列表
    fileInput.value.files = files.value;
    // 检查是否有文件被选择
    if (files.value.length === 0) {
      Notify.create({
        type: 'negative',
        message: '请先选择文件！'
      });
      return;
    }

    // 这里可以添加你的上传文件逻辑
    const formData = new FormData();
    // 遍历用户选择的文件，将每个文件附加到 FormData 对象中
    for (let i = 0; i < files.value.length; i++) {
      formData.append('images', files.value[i]); // 'images' 是后端接收的字段名
    }
    let result = await postUploads(formData);
    images.value = result.data.paths;
    if (result.success) {
      Notify.create({
        position: 'top',
        type: 'positive',
        message: result.msg
      });
      return;
    }

    Notify.create({
      type: 'negative',
      message: result.msg
    });
  } finally {
    imagesLoading.value = false;
  }
}

function removeImage(index) {
  // 删除文件时，从列表中移除
  files.value.splice(index, 1);
  images.value.splice(index, 1);
  // 更新q-uploader的文件列表
  fileInput.value.files = files.value;
}
async function sendMessage() {
  await useMsgStores().sendMeMsg({
    text: textareaModel.value,
    images: JSON.parse(JSON.stringify(images.value))
  });
  if (!textareaModel.value || isLoading.value) return;
  isLoading.value = true;
  try {
    // 在这里调用你的发送消息接口
    let id = await useMsgStores().sendBatMsg({
      sent: false,
      text: '',
      loading: true
    });
    let messages = useMsgStores().currentMesg.msgData.map(item => {
      let content = item.text;
      if (item?.images?.length > 0) {
        const images = item.images.map(url => {
          return {
            type: 'image_url',
            image_url: {
              url
            }
          };
        });
        content = [
          {
            type: 'text',
            text: item.text
          },
          ...images
        ];
      }
      return {
        role: item.sent ? 'user' : 'system',
        content
      };
    });
    let result = await getGptReply(messages);
    const reader = result.body.getReader();

    const decoder = new TextDecoder();
    let done = false;
    let buffer = ''; // 缓存流中的数据

    while (!done) {
      const { value, done: streamDone } = await reader.read();
      console.log(streamDone);
      done = streamDone;
      if (done) break;
      // 解码每个流的数据块
      buffer += decoder.decode(value, { stream: true });
      // 将 buffer 中的 `data: ` 前缀去除，并分割成 JSON 对象
      const parts = buffer.split('\n\n');
      console.log(JSON.parse(JSON.stringify(parts)));
      for (let part of parts) {
        if (part.startsWith('data: ')) {
          const jsonString = part.replace(/^data: /, '').trim();
          // 过滤掉 [DONE] 标记
          if (jsonString !== '[DONE]') {
            try {
              const json = JSON.parse(jsonString);
              useMsgStores().updateMsg(id, json?.choices[0]?.delta?.content);
              // console.log('Parsed JSON:', json);
            } catch (err) {
              console.error('Error parsing JSON:', err, jsonString);
            }
          }
        } else {
          console.log(part);
          // 说明出错了
          if (part) {
            useMsgStores().updateMsg(id, JSON.parse(part).error.message);
          }
        }
      }
      // 清空 buffer 以处理下一个流块
      buffer = parts[parts.length - 1];
    }
    textareaModel.value = ''; // 清空输入框
    images.value = []; // 清空输入框
    files.value = []; // 清空输入框
    fileInput.value.files = files.value;
  } catch (error) {
    console.error('发送消息失败:', error);
  } finally {
    isLoading.value = false;
  }
}
const linksList = ref([]);
const createHeart = () => {
  if (!useSettingStores().lovingState && lovingTime.value) {
    clearInterval(lovingTime.value);
    lovingTime.value = null;
  }
  const heart = document.createElement('div');
  heart.className = 'heart';
  heart.innerHTML = '❤️';

  const textElement = document.querySelector('.gradient-text');
  const addElem = document.querySelector('.gradient-text-box');
  const rect = textElement.getBoundingClientRect();
  const randomX = Math.random() * rect.width;
  const randomY = Math.random() * rect.height;

  heart.style.left = rect.left / 2 + randomX / 2 + 'px';
  heart.style.top = rect.top + randomY + 'px';

  heart.style.position = 'absolute';
  heart.style.color = '#ff007f';
  heart.style.fontSize = '24px'; /* 默认大小 */
  // heart.style.opacity = 0;

  addElem.appendChild(heart);

  // 计算随机方向
  const angle = Math.random() * 2 * Math.PI; // 随机角度
  const distance = Math.random() * 10 + 50; // 随机距离

  heart.animate(
    [
      { transform: 'translate(0, 0)', opacity: 1, fontSize: '6px' },
      {
        fontSize: '24px',
        transform: `translate(${Math.cos(angle) * distance}px, ${
          Math.sin(angle) * distance
        }px)`,
        opacity: 0
      }
    ],
    {
      duration: 2000,
      easing: 'ease-in-out',
      fill: 'forwards'
    }
  );

  setTimeout(() => {
    heart.remove();
  }, 2000);
};
watch(
  () => useSettingStores().lovingState,
  newLovingState => {
    if (newLovingState) {
      lovingTime.value = setInterval(createHeart, 200); // 每500毫秒生成一个爱心
    }
  },
  {
    immediate: true
  }
);
// 侦听 params.id 的变化
watch(
  () => route.params.id,
  newId => {
    useMsgStores().setMsgId(parseInt(newId));
    // 在这里可以添加其他逻辑，例如获取数据
    console.log(`Item ID changed to: ${newId}`);
  }
);
watch(
  () => useMsgStores().conversationHistory,
  newData => {
    if (!newData || !newData.length) return;
    linksList.value = newData.map((item, index) => {
      return {
        link: useMsgStores().conversationHistory[index].id,
        icon: 'mail',
        title: item?.msgData[0]?.text?.substring(0, 6) || '新的聊天记录'
      };
    });
  },
  {
    deep: true,
    immediate: true
  }
);

const leftDrawerOpen = ref(false);
const rightDrawerOpen = ref(false);

function toggleLeftDrawer() {
  leftDrawerOpen.value = !leftDrawerOpen.value;
}

function toggleRightDrawer() {
  rightDrawerOpen.value = !rightDrawerOpen.value;
}
// const $q = useQuasar();
function openForm() {
  prompt.value = true;
}
async function sendEmail() {
  try {
    fasonyoujLoading.value = true;
    let result = await postSendEmail({
      text: emailMsg.value
    });
    Notify.create({
      position: 'top',
      type: 'positive',
      message: result.msg
    });
  } catch (error) {
    Notify.create({
      position: 'top',
      type: 'negative',
      message: result.msg
    });
  } finally {
    prompt.value = false;
    fasonyoujLoading.value = false;
  }
}
onMounted(() => {
  // lovingTime.value = setInterval(createHeart, 200); // 每500毫秒生成一个爱心
});
</script>
<style scoped>
.image-container {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  position: relative; /* 设置为相对定位以便于按钮定位 */
  margin-right: 10px; /* 图像之间的间距 */
}

.preview-image {
  width: 50px; /* 设置预览图像的宽度 */
  height: auto; /* 高度自动 */
}

.delete-button {
  position: absolute; /* 绝对定位 */
  top: 5px; /* 距离顶部5像素 */
  right: 5px; /* 距离右侧5像素 */
  padding: 2px; /* 调整按钮内边距以减小按钮大小 */
}

:deep(.q-field__control) {
  align-items: flex-end;
}
.gradient-text {
  background: linear-gradient(
    90deg,
    #ff007f,
    #ff7f00,
    #7fff00,
    #00ff7f,
    #007fff,
    #0000ff
  );
  background-size: 300% 100%;
  animation: gradientAnimation 5s ease infinite;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  position: relative;
}
@keyframes gradientAnimation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
.heart {
  position: absolute;
  color: #ff007f;
  font-size: 24px; /* 默认大小 */
  opacity: 0;
}

.chat-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.drawer-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.drawer-header {
  flex-shrink: 0;
}

.drawer-body {
  flex-grow: 1;
  overflow-y: auto;
}

.drawer-footer {
  flex-shrink: 0;
}
</style>
